/**
 * Copyright 2019 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.fos;

import java.lang.reflect.Constructor;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 客户端工厂
 * 
 * @author jianggujin
 *
 */
public class JClientFactory {
    /**
     * 创建新的客户端
     * 
     * @param configuration
     * @return
     * @throws JFOSException
     */
    @SuppressWarnings("unchecked")
    public static <T extends JClient> T newClient(JConfiguration<T> configuration) throws JFOSException {
        try {
            Class<?> configurationClass = configuration.getClass();
            Class<?> clientClass = getClientClass((Class<? extends JClient>) configurationClass);
            return (T) getConstructor(clientClass, configurationClass).newInstance(configuration);
        } catch (Exception e) {
            throw new JFOSException(e.getMessage(), e);
        }
    }

    /**
     * 获取客户端类
     *
     * @param clazz
     * @return
     * @throws JFOSException
     */
    private static Class<?> getClientClass(Class<?> configurationClass) throws JFOSException {
        Type[] types = configurationClass.getGenericInterfaces();
        for (Type type : types) {
            if (type instanceof ParameterizedType) {
                Type[] items = ((ParameterizedType) type).getActualTypeArguments();
                if (items != null) {
                    for (Type item : items) {
                        if (JClient.class.isAssignableFrom((Class<?>) item)) {
                            return (Class<?>) item;
                        }
                    }
                }
            }
        }
        throw new JFOSException("parse client class error.");
    }

    /**
     * 获得构造方法
     * 
     * @param clientClass
     * @param configurationClass
     * @return
     * @throws NoSuchMethodException
     * @throws SecurityException
     */
    private static Constructor<?> getConstructor(Class<?> clientClass, Class<?> configurationClass)
            throws NoSuchMethodException, SecurityException {
        try {
            return clientClass.getConstructor(configurationClass);
        } catch (NoSuchMethodException e) {
            return clientClass.getConstructor(JConfiguration.class);
        }
    }
}
